//
//  RecipesDetailViewController.m
//  SVN_Tuan_Thuy
//
//  Created by HOCVIEN on 4/21/15.
//  Copyright (c) 2015 Module4. All rights reserved.
//

#import "RecipesDetailViewController.h"
@interface RecipesDetailViewController ()
@property (weak, nonatomic) IBOutlet UIImageView *imgRecipes;
@property (weak, nonatomic) IBOutlet UITextView *lblDetails;
@property (weak, nonatomic) IBOutlet UIButton *btnNext;
@property (weak, nonatomic) IBOutlet UIButton *btnPrevious;
@property (nonatomic) NSArray *ingredients;
@property (strong, nonatomic) IBOutlet UIImageView *imgBackGround;
@property (strong, nonatomic) UIActivityIndicatorView *waiting;
@property (nonatomic) NSUInteger currentIndex;
@end

@implementation RecipesDetailViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
}
- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];

    [self loadIngredientsByFoodId:self.food.foodID];

    UIBlurEffect *blur = [UIBlurEffect effectWithStyle:UIBlurEffectStyleLight];
    UIVisualEffectView *blurView = [[UIVisualEffectView alloc] initWithEffect:blur];
    blurView.frame = self.imgBackGround.bounds;
    //self.imgBackGround.alpha = 0.5;
    [self.imgBackGround addSubview:blurView];
    self.imgBackGround.contentMode = UIViewContentModeCenter;
    [self waitingSetting];
}

- (void)loadIngredientsByFoodId:(NSString *)foodId {
    [self.waiting startAnimating];
    self.currentIndex = [[AppUtils defaultAppUtils].foodListId indexOfObject:foodId];

    self.lblDetails.text = @"Loading...";
    self.navigationItem.title = @"Loading...";

    self.imgRecipes.image = [[SAMCache sharedCache] imageForKey:foodId];
    self.imgBackGround.image = [[SAMCache sharedCache] imageForKey:foodId];

    NSString *ingredientCache = [[SAMCache sharedCache] objectForKey:[NSString stringWithFormat:@"ingredient-%@", foodId]];
    NSString *title = [[SAMCache sharedCache] objectForKey:[NSString stringWithFormat:@"title-%@", foodId]];

    if (ingredientCache && title) {
        self.lblDetails.text = ingredientCache;
        self.navigationItem.title = title;
        [self.waiting stopAnimating];
        return;
    }
    NSString *requestUrlString = [NSString stringWithFormat:@"http://food2fork.com/api/get?key=cbabb661c0146d117f6ab6866c6017ed&rId=%@", foodId];
    NSURL *requestUrl = [NSURL URLWithString:requestUrlString];
    NSURLRequest *request = [NSURLRequest requestWithURL:requestUrl];
    __block NSString *ingredientString = @"";
    [NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) {
        NSError *error;
        NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:data options:0 error:&error];
        NSDictionary *recipe = [dic objectForKey:@"recipe"];
        NSArray *ingredients = [recipe objectForKey:@"ingredients"];
        NSString * title = [recipe objectForKey:@"title"];
        self.navigationItem.title = title;
        //NSLog(@"%@",ingredients);
        for (NSString * ingredient in ingredients) {
            ingredientString = [ingredientString stringByAppendingString:[NSString stringWithFormat:@"+ %@ \n",ingredient]];
        }
        //NSLog(@"%@",ingredientString);
        self.lblDetails.text = ingredientString;
        [[SAMCache sharedCache] setObject:ingredientString forKey:[NSString stringWithFormat:@"ingredient-%@", foodId]];
        [[SAMCache sharedCache] setObject:title forKey:[NSString stringWithFormat:@"title-%@", foodId]];
[self.waiting stopAnimating];
    }];
}

- (IBAction)onTouchNextButton:(id)sender {
    NSInteger count = [[AppUtils defaultAppUtils].foodListId count];
    NSInteger nextId = self.currentIndex + 1;

    if (nextId < count) {
        NSString *nextRecipeId = [[AppUtils defaultAppUtils].foodListId objectAtIndex:nextId];
        [self loadIngredientsByFoodId:nextRecipeId];
    } else {
        [self showCannotGoFurther:@"This is last of food list"];
    }
}
- (IBAction)onTouchPrevButton:(id)sender {
    //NSUInteger count = [[AppUtils defaultAppUtils].foodListId count];
    NSInteger nextId = self.currentIndex - 1;

    if (nextId > -1) {
        NSString *nextRecipeId = [[AppUtils defaultAppUtils].foodListId objectAtIndex:nextId];
        [self loadIngredientsByFoodId:nextRecipeId];
    } else {
        [self showCannotGoFurther:@"This is first of food list"];
    }
}
- (void)showCannotGoFurther:(NSString *)message {
    UIAlertView *alert = [[UIAlertView alloc] initWithTitle:message message:nil delegate:nil cancelButtonTitle:nil otherButtonTitles:nil];
    [alert show];

    double delayInSeconds = 2.0;
    dispatch_time_t popTime = dispatch_time(DISPATCH_TIME_NOW, (int64_t)(delayInSeconds * NSEC_PER_SEC));
    dispatch_after(popTime, dispatch_get_main_queue(), ^(void) {
        [alert dismissWithClickedButtonIndex:0 animated:YES];
    });
}

- (void)waitingSetting {
    self.waiting = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleWhiteLarge];
    self.waiting.color = [AppUtils themeFontColor];
    self.waiting.center = self.view.center;
    self.waiting.hidesWhenStopped = true;
    [self.view addSubview:self.waiting];
}
@end
